<template>
  <div class="goods-add">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ name: 'Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品编辑</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row class="steps">
      <el-steps :active="active">
        <el-step
          v-for="(item, index) in steps"
          :key="item"
          :title="item"
          :icon="icons[index]"
        ></el-step>
      </el-steps>
    </el-row>
    <el-row class="form-wrap" v-show="active === 1">
      <el-form
        :rules="addFormRules"
        :model="addForm"
        size="small"
        label-position="left"
        label-width="80px"
        class="add-form"
        inline
        ref="form"
      >
        <el-form-item prop="goods_name" class="goods-name" label="商品名称">
          <el-input
            class="goods-name-input"
            v-model="addForm.goods_name"
          ></el-input>
        </el-form-item>
        <el-form-item prop="goods_number" label="商品数量">
          <el-input v-model="addForm.goods_number"></el-input>
        </el-form-item>
        <el-form-item class="goods-weight" prop="goods_weight" label="商品重量">
          <el-input v-model="addForm.goods_weight"></el-input>
        </el-form-item>
        <el-form-item prop="goods_price" label="商品价格">
          <el-input v-model="addForm.goods_price"></el-input>
        </el-form-item>
        <el-form-item prop="goods_cat" label="商品分类">
          <el-cascader
            disabled
            v-model="addForm.goods_cat"
            :options="categories"
            :props="{ expandTrigger: 'hover', ...cateProps }"
          ></el-cascader>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row class="form-wrap" v-show="active === 2">
      <el-row class="tags" v-for="attr in attrs" :key="attr.attr_id">
        <span>{{ attr.attr_name }}: </span>
        <el-tag
          closable
          v-for="(val, index) in attr.attr_vals"
          :key="index"
          @close="handleClose(attr.attr_vals, index)"
          >{{ val }}</el-tag
        >
      </el-row>
    </el-row>
    <el-row class="form-wrap" v-show="active === 3">
      <el-row v-for="param in params" :key="param.attr_id">
        <h2>{{ param.attr_name }}</h2>
        <el-input v-model="param.attr_vals"></el-input>
      </el-row>
    </el-row>
    <el-row class="form-wrap" v-show="active === 4">
      <input type="file" />
      <el-upload
        class="upload-demo"
        :headers="{ Authorization: $store.state.token }"
        :action="baseURL + '/upload'"
        :file-list="fileList"
        :on-success="handleUpload"
        list-type="picture"
        :on-remove="handleRm"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
    </el-row>
    <el-row class="form-wrap" v-show="active === 5">
      <quill-editor v-model="content"> </quill-editor>
    </el-row>
    <el-row class="footer-btns">
      <el-button
        size="small"
        type="primary"
        v-if="active > 1"
        @click="handleStep(-1)"
        >上一步</el-button
      >
      <el-button
        size="small"
        type="primary"
        v-if="active < 5"
        @click="handleStep(1)"
        :disabled="subBtnStatus"
        >下一步</el-button
      >
      <el-button
        size="small"
        @click="editGoods"
        type="primary"
        :disabled="subBtnStatus"
        >提交</el-button
      >
    </el-row>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
import { getCategories, getAttrs, getGoodsDetail, editGoods } from "@/http/api";
import baseURL from "@/http";
export default {
  data() {
    return {
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: "",
      },
      subBtnStatus: true,
      addFormRules: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: ["blur", "change"],
          },
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: ["blur", "change"],
          },
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: ["blur", "change"],
          },
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: ["blur", "change"],
          },
        ],
        goods_cat: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: ["blur", "change"],
          },
        ],
      },
      categories: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
      },
      steps: ["基本信息", "商品参数", "商品属性", "商品图片", "商品内容"],
      icons: [
        "el-icon-edit",
        "el-icon-edit",
        "el-icon-edit",
        "el-icon-edit",
        "el-icon-edit",
      ],
      active: 1,
      attrs: [],
      handleSteps: {
        1: () => {},
        2: this.getAttrs,
        3: this.getParams,
        4: () => {},
        5: () => {},
      },
      params: [],
      baseURL: "",
      fileList: [],
      uploadList: [],
      content: "",
    };
  },
  components: {
    quillEditor,
  },
  watch: {
    // addForm: {
    //   deep: true,
    //   immediate: true,
    //   handler() {
    //     this.$nextTick(() => {
    //       this.$refs.form.validate((valid) => {
    //         if (valid) {
    //           this.subBtnStatus = false;
    //         } else {
    //           this.subBtnStatus = true;
    //           this.$refs.form.clearValidate();
    //           return false;
    //         }
    //       });
    //     });
    //   },
    // },
    addForm: {
      deep: true,
      handler() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.subBtnStatus = false;
          } else {
            this.subBtnStatus = true;
            this.$refs.form.clearValidate();
            return false;
          }
        });
      },
    },
    active(val) {
      // if (val === 2) {
      //   this.getAttrs();
      // }else if(va)
      // switch (val) {
      //   case 2:

      //     break;

      //   default:
      //     break;
      // }
      this.handleSteps[val]();
    },
  },
  methods: {
    //获取商品详情
    async getGoodsDetail() {
      const res = await getGoodsDetail(this.$route.params.id);
      const cats = res.goods_cat.split(",");
      //   console.log(cats);
      //   cats.forEach((item) => (item = Number(item)));
      res.goods_cat = cats.map((item) => +item);
      this.addForm = res;
      this.$nextTick(() => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.subBtnStatus = false;
          } else {
            this.subBtnStatus = true;
            this.$refs.form.clearValidate();
            return false;
          }
        });
      });
      //处理商品参数和商品属性
      this.attrs = res.attrs.filter((item) => item.attr_sel == "many");
      this.attrs.forEach((item) => {
        if (item.attr_value) {
          item.attr_vals = item.attr_value.split(",");
        } else {
          item.attr_vals = [];
        }
      });
      this.params = res.attrs.filter((item) => item.attr_sel == "only");
      this.fileList = res.pics.map((item) => ({
        name: item.pics_big,
        url: item.pics_big_url.replace(/t:/g, "t:8888"),
      }));
      this.content = res.goods_introduce;
      console.log(res);
    },
    //获取三级分类列表
    async getCategories() {
      const res = await getCategories();
      this.categories = res;
      console.log(res);
    },
    //编辑商品
    async editGoods() {
      const pics = this.fileList.map((item) => {
        //匹配编辑图片路径，正则改写
        if (!item.name.includes("tem_uploads")) {
          return {
            pic: item.name.replace(/(\/uploads.*big_)/, "tmp_uploads/"),
          };
        } else {
          return { pic: item.name };
        }
      });
      await editGoods({
        ...this.addForm,
        goods_cat: this.addForm.goods_cat.join(","),
        goods_introduce: this.content,
        pics,
        attrs: [
          ...this.attrs.map((item) => ({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          })),
          ...this.params.map((item) => {
            return {
              attr_id: item.attr_id,
              attr_value: item.attr_vals,
            };
          }),
        ],
      });
      this.$router.go(-1);
    },
    //步骤条
    handleStep(num) {
      this.active += num;
    },
    //获取商品参数
    async getAttrs() {
      if (this.attrs.length > 0) return;
      const res = await getAttrs({
        id: this.addForm.goods_cat[this.addForm.goods_cat.length - 1],
        sel: "many",
      });
      //循环res列表，把attr_vals 字符串转化为 数组
      res.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
      });
      this.attrs = res;
    },
    //获取商品属性
    async getParams() {
      if (this.params.length > 0) return;
      const res = await getAttrs({
        id: this.addForm.goods_cat[this.addForm.goods_cat.length - 1],
        sel: "only",
      });
      this.params = res;
      console.log(res);
    },
    //删除默认属性
    handleClose(vals, index) {
      vals.splice(index, 1);
    },
    //上传成功回调
    handleUpload(res) {
      this.$message.success(res.meta.msg);
      this.fileList.push({
        name: res.data.tmp_path,
        url: res.data.url.replace(/t:/g, "t:8888"),
      });
      console.log(res);
    },
    //删除已上传图片
    handleRm(val, list) {
      let index = this.fileList.findIndex((item) => item.url === val.url);
      this.fileList.splice(index, 1);
      console.log(val, list);
    },
  },
  created() {
    this.getGoodsDetail();
    this.getCategories();
    this.baseURL = baseURL;
  },
};
</script>

<style scoped lang="stylus">
.goods-add
    position relative
    height calc(100vh - 100px)
    .steps
        padding 15px 0
        border-bottom 1px solid #eee
    .form-wrap
        padding 15px 0
        .tags
            display flex
            gap 15px
            align-items center
        .add-form
            width 600px
            .goods-name
                width 100%
                .goods-name-input
                    width 100%
                ::v-deep .el-form-item__content
                    width 485px
            .goods-weight
                ::v-deep .el-form-item__content
                    width 205px
    .footer-btns
        position absolute
        bottom 0
        left 0
        border-top 1px solid #eee
        right 0
        padding 20px 0 0 0
        box-shadow inset 0 -8px 4px 4px rgb(255,255,255),inset 0 2px 4px 0px rgba(50, 50, 50, 0.75)
</style>
